package net.e_agri.action;

import java.io.IOException;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.e_agri.wap.HttpMethod;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@SuppressWarnings("serial")
public class Authentication implements Serializable{

	private static final Log log = LogFactory.getLog(Authentication.class);

	private String rootUri = null;

	private String uid = null;

	private String pwd = null;
	
	private String sessid = null;

	/**
	 * @return the rootUri
	 */
	public String getRootUri() {
		return rootUri;
	}

	/**
	 * @param rootUri the rootUri to set
	 */
	public Authentication setRootUri(String rootUri) {
		this.rootUri = rootUri;
		return this;
	}

	/**
	 * @return the uid
	 */
	public String getUid() {
		return uid;
	}

	/**
	 * @param uid the uid to set
	 */
	public Authentication setUid(String uid) {
		this.uid = uid;
		return this;
	}

	/**
	 * @return the pwd
	 */
	public String getPwd() {
		return pwd;
	}

	/**
	 * @param pwd the pwd to set
	 */
	public Authentication setPwd(String pwd) {
		this.pwd = pwd;
		return this;
	}

	/**
	 * @return the sessid
	 */
	public String getSessid() {
		return sessid;
	}

	/**
	 * @param sessid the sessid to set
	 */
	private void setSessid(String sessid) {
		this.sessid = sessid;
	}

	public void logIn() throws IOException{
		logIn(this.uid, this.pwd);
	}

	public void logIn(String id, String pass) throws IOException{
		
		setUid(id);
		setPwd(pass);
		Map<String,String> params = new LinkedHashMap<String,String>();
			params.put("m", "pc");
			params.put("a", "do_o_login");
			params.put("login_params", "");
			params.put("username", getUid());
			params.put("password", getPwd());

		String content = HttpMethod.doPost(rootUri,
				//rootUri.substring(0, rootUri.lastIndexOf("/")),
				params);

		String pattern = "&amp;sessid=([^\"]*)\\\"";
		Matcher mat = Pattern.compile(pattern).matcher(content);
		if(mat.find())
			setSessid(mat.group(1));
		else
			log.info("sessid not found.:" + pattern);
	}

	public void logOut() throws IOException{
		HttpMethod.doGet(rootUri + "./?m=pc&amp;a=do_inc_page_header_logout&amp;sessid=" + getSessid());
		log.info("logout : " + getSessid());
	}
}
